/**
 *  test16.c - Test for RTC.
 *
 *  Copyright (C) 2008-2010 ZhangHu
 *  All rights reserved.
 *  E-MAIL: anmnmnly@gmail.com
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
#include "include/core.h"
#include "drivers/uart_console.h"
#include "drivers/chdev.h"
#include "drivers/rtc.h"
#include "devs.h"


#define STACK_SIZE 4096


static const char_t weekday[7][16] = {
    "Sunday", "Monday", "Tuesday", "Wednesday",
    "Thursday", "Friday", "Saturday"
};


void print_time(const rtc_t *rtc_time)
{

    if(rtc_time == NULL) {
        return;
    }

    Print("%4x-%2x-%2x, ", rtc_time->year, rtc_time->month, rtc_time->day);
    Print("%s. ", weekday[rtc_time->weekday - 1]);

    Print("%2x:%2x:%2x\n", rtc_time->hour, rtc_time->min, rtc_time->sec);
}



static void Task0(void)
{
    chdev_t *dev = NULL;
    rtc_t rtc_time = {0};

    while(1) {
        dev = CDevOpen(RTC);
        if(dev == NULL) {
            Print("Task0: Cann't open RTC!\n");
            osWait(100);
            continue;
        }

        CDevIoctl(dev, RTC_CMD_READ, &rtc_time);
        CDevClose(dev);

        Print("Task0: ");
        print_time(&rtc_time);

        osWait(100);
    }
}



static void Task1(void)
{
    chdev_t *dev = NULL;
    rtc_t rtc_time = {0};

    while(1) {
        dev = CDevOpen(RTC);
        if(dev == NULL) {
            Print("Task1: Cann't open RTC!\n");
            osWait(100);
            continue;
        }

        CDevIoctl(dev, RTC_CMD_READ, &rtc_time);
        CDevClose(dev);

        Print("Task1: ");
        print_time(&rtc_time);

        osWait(100);
    }
}



void Main(void)
{
    chdev_t *dev = NULL;
    rtc_t rtc_time;

    // Init time is 2010-9-30 23:59:59.
    rtc_time.year = 0x10;
    rtc_time.month = 0x9;
    rtc_time.day = 0x30;
    rtc_time.weekday = THU;
    rtc_time.hour = 0x23;
    rtc_time.min = 0x59;
    rtc_time.sec = 0x59;

    dev = CDevOpen(RTC);
    if(dev == NULL) {
        Print("Task: Cann't open RTC!\n");
        osWait(100);
    }

    CDevIoctl(dev, RTC_CMD_WRITE, &rtc_time);
    CDevClose(dev);

    osInitTask(Task0, 100, 0, 5, STACK_SIZE);
    osInitTask(Task1, 101, 1, 5, STACK_SIZE);
}

